<template>
  <div class="events-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <el-breadcrumb>
          <el-breadcrumb-item
            v-for="(crumb, index) in breadcrumbs"
            :key="index"
            :to="index === breadcrumbs.length - 1 ? null : { path: crumb.path }"
          >
            {{ crumb.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="container mx-auto px-4 py-6">
        <div class="flex justify-between items-center mb-6">
          <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
            活动日历
          </h1>
          <div class="flex items-center gap-4">
            <el-button
              type="primary"
              :icon="Calendar"
              @click="$router.push('/user/activities')"
            >
              我参与的活动
            </el-button>
            <el-button
              type="primary"
              :icon="Edit"
              @click="showCreateEventDialog = true"
            >
              发布活动
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- 左侧日历和筛选 -->
        <div class="lg:col-span-1">
          <div class="sticky top-24 space-y-6">
            <!-- 日历组件 -->
            <div
              class="calendar-card bg-white dark:bg-gray-800 rounded-xl shadow-md p-6"
            >
              <h3
                class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
              >
                <el-icon class="mr-2 text-primary-500"><Calendar /></el-icon>
                活动日期
              </h3>
              <el-date-picker
                v-model="selectedDate"
                type="month"
                format="YYYY年MM月"
                value-format="YYYY-MM"
                class="!w-full custom-date-picker"
                :shortcuts="dateShortcuts"
                :locale="zhCn"
                :placeholder="'选择月份'"
                @change="handleDateChange"
              />
              <div class="mt-6 space-y-4">
                <div
                  class="flex items-center justify-between p-3 rounded-lg bg-primary-50 dark:bg-primary-900/20"
                >
                  <span class="text-sm text-gray-600 dark:text-gray-400"
                    >本月活动</span
                  >
                  <span
                    class="text-lg font-medium text-primary-600 dark:text-primary-400"
                    >{{ currentMonthEvents.length }}场</span
                  >
                </div>
                <div
                  class="flex items-center justify-between p-3 rounded-lg bg-green-50 dark:bg-green-900/20"
                >
                  <span class="text-sm text-gray-600 dark:text-gray-400"
                    >进行中</span
                  >
                  <span
                    class="text-lg font-medium text-green-600 dark:text-green-400"
                    >{{ ongoingEvents.length }}场</span
                  >
                </div>
                <div
                  class="flex items-center justify-between p-3 rounded-lg bg-yellow-50 dark:bg-yellow-900/20"
                >
                  <span class="text-sm text-gray-600 dark:text-gray-400"
                    >即将开始</span
                  >
                  <span
                    class="text-lg font-medium text-yellow-600 dark:text-yellow-400"
                    >{{ upcomingEvents.length }}场</span
                  >
                </div>
              </div>
              <template v-if="selectedDateEvents.length > 0">
                <div class="mt-6">
                  <h4
                    class="text-sm font-medium text-gray-900 dark:text-white mb-3"
                  >
                    当前选中日期活动
                  </h4>
                  <div class="space-y-3">
                    <div
                      v-for="event in selectedDateEvents"
                      :key="event.id"
                      class="flex items-center p-3 rounded-lg bg-gray-50 dark:bg-gray-700/50 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors cursor-pointer"
                      @click="scrollToEvent(event.id)"
                    >
                      <div
                        class="w-2 h-2 rounded-full"
                        :class="getEventTypeColor(event.type)"
                      ></div>
                      <span
                        class="ml-2 text-sm text-gray-700 dark:text-gray-300 line-clamp-1"
                        >{{ event.title }}</span
                      >
                    </div>
                  </div>
                </div>
              </template>
            </div>

            <!-- 活动分类 -->
            <div
              class="category-card bg-white dark:bg-gray-800 rounded-xl shadow-md p-6"
            >
              <h3
                class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
              >
                <el-icon class="mr-2 text-primary-500"><Menu /></el-icon>
                活动分类
              </h3>
              <el-checkbox-group
                v-model="selectedTypes"
                class="flex flex-col space-y-3"
                @change="handleTypeChange"
              >
                <el-checkbox
                  v-for="type in eventTypes"
                  :key="type.value"
                  :label="type.value"
                  class="category-checkbox !flex items-center p-3 rounded-lg transition-colors hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  <div class="flex items-center">
                    <div
                      class="w-8 h-8 rounded-lg bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center mr-3"
                    >
                      <el-icon class="text-primary-500 dark:text-primary-400"
                        ><component :is="type.icon"
                      /></el-icon>
                    </div>
                    <span>{{ type.label }}</span>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>

        <!-- 右侧活动列表 -->
        <div class="lg:col-span-3">
          <!-- 筛选工具栏 -->
          <div
            class="filter-card bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 mb-6"
          >
            <div
              class="flex flex-col md:flex-row md:items-center md:space-x-4 space-y-4 md:space-y-0"
            >
              <el-input
                v-model="searchQuery"
                placeholder="搜索活动"
                class="flex-1"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
                <template #append>
                  <el-button @click="handleSearch">搜索</el-button>
                </template>
              </el-input>
              <el-radio-group
                v-model="timeRange"
                size="large"
                class="flex-shrink-0"
                @change="handleTimeRangeChange"
              >
                <el-radio-button label="all">全部活动</el-radio-button>
                <el-radio-button label="upcoming">即将开始</el-radio-button>
                <el-radio-button label="ongoing">正在进行</el-radio-button>
                <el-radio-button label="ended">已结束</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 活动列表 -->
          <div v-loading="loading" class="space-y-6">
            <div
              v-for="event in paginatedEvents"
              :key="event.id"
              :id="`event-${event.id}`"
              class="event-card bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden hover:shadow-lg transition-all duration-300"
              @click="handleEventClick(event)"
            >
              <div class="flex flex-col md:flex-row">
                <div class="relative md:w-48 flex-shrink-0">
                  <el-image
                    :src="event.image"
                    class="w-full h-48 md:h-full object-cover transition-transform duration-300 hover:scale-105"
                    fit="cover"
                  >
                    <template #placeholder>
                      <div class="image-placeholder h-full">
                        <el-icon class="text-4xl"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="absolute top-4 left-4 flex space-x-2">
                    <el-tag
                      :type="getEventStatusType(event.status)"
                      class="event-status-tag"
                      effect="dark"
                    >
                      {{ getEventStatusText(event.status) }}
                    </el-tag>
                  </div>
                </div>
                <div class="flex-1 p-6">
                  <div class="flex flex-col h-full">
                    <div class="flex items-start justify-between mb-4">
                      <div>
                        <div class="flex items-center space-x-2 mb-2">
                          <el-tag>{{ event.type }}</el-tag>
                        </div>
                        <h3
                          class="text-xl font-bold text-gray-900 dark:text-white"
                        >
                          {{ event.title }}
                        </h3>
                      </div>
                      <el-button
                        type="primary"
                        class="register-btn"
                        :disabled="event.status === 'ended'"
                        @click.stop="handleRegister(event)"
                      >
                        {{ event.status === "ended" ? "已结束" : "立即报名" }}
                      </el-button>
                    </div>
                    <p
                      class="text-gray-600 dark:text-gray-400 mb-4 line-clamp-2"
                    >
                      {{ event.description }}
                    </p>
                    <div
                      class="flex flex-wrap items-center gap-4 text-sm text-gray-500 dark:text-gray-400 mt-auto"
                    >
                      <span class="flex items-center">
                        <el-icon class="mr-1"><Calendar /></el-icon>
                        {{ formatEventTime(event.startTime, event.endTime) }}
                      </span>
                      <span class="flex items-center">
                        <el-icon class="mr-1"><Location /></el-icon>
                        {{ event.location }}
                      </span>
                      <span class="flex items-center">
                        <el-icon class="mr-1"><User /></el-icon>
                        已报名 {{ formatNumber(event.registeredCount) }} 人
                      </span>
                      <div class="flex-1"></div>
                      <el-progress
                        :percentage="
                          Math.round(
                            (event.registeredCount / event.maxParticipants) *
                              100,
                          )
                        "
                        :status="getProgressStatus(event)"
                        class="w-32"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 无数据提示 -->
            <el-empty v-if="paginatedEvents.length === 0" description="暂无活动数据" />
          </div>

          <!-- 分页 -->
          <div class="flex justify-center mt-8">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="filteredEvents.length"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 创建活动弹窗 -->
    <el-dialog
      v-model="showCreateEventDialog"
      title="发布活动"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="create-event-dialog">
        <p class="text-center text-gray-600 dark:text-gray-400 mb-6">
          您需要登录并拥有发布活动权限才能创建活动
        </p>
        <div class="flex justify-center">
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="showCreateEventDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 联系主办方弹窗 -->
    <el-dialog
      v-model="showContactDialog"
      title="联系主办方"
      width="40%"
    >
      <div class="contact-dialog">
        <div class="flex items-center mb-6">
          <el-avatar :size="48" :src="currentEvent?.organizer?.avatar || ''" class="mr-4"></el-avatar>
          <div>
            <h3 class="text-lg font-medium">{{ currentEvent?.organizer?.name || '' }}</h3>
            <p class="text-gray-500">活动主办方</p>
          </div>
        </div>
        <el-form>
          <el-form-item label="联系方式">
            <p>电话: 0775-12345678</p>
            <p>邮箱: organizer@example.com</p>
          </el-form-item>
          <el-form-item label="留言">
            <el-input type="textarea" :rows="4" placeholder="请输入您想咨询的问题" v-model="contactMessage"></el-input>
          </el-form-item>
        </el-form>
        <div class="flex justify-end mt-4">
          <el-button type="primary" @click="submitContact">发送消息</el-button>
          <el-button @click="showContactDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 注册活动弹窗 -->
    <el-dialog
      v-model="showRegisterDialog"
      title="活动报名"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="register-dialog">
        <h3 class="text-lg font-medium mb-4">{{ currentEvent?.title || '' }}</h3>
        <el-form
          ref="registrationForm"
          :model="registrationForm"
          :rules="registrationRules"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="registrationForm.name" placeholder="请输入您的姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="registrationForm.phone" placeholder="请输入您的手机号码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="registrationForm.email" placeholder="请输入您的邮箱"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="3" v-model="registrationForm.remark" placeholder="请输入备注信息（选填）"></el-input>
          </el-form-item>
        </el-form>
        <div class="flex justify-end mt-4">
          <el-button type="primary" @click="submitRegistration">提交报名</el-button>
          <el-button @click="showRegisterDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Calendar,
  Location,
  User,
  ArrowLeft,
  ArrowRight,
  Back,
  Menu,
  Picture,
  Collection,
  Medal,
  Present,
  TrendCharts,
  Sunny,
  Edit,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import service from "@/api/axios";

const router = useRouter();
const route = useRoute();

// 根据来源路径生成面包屑
const breadcrumbs = computed(() => {
  const baseCrumb = [{ name: "首页", path: "/" }];

  // 检查路由来源
  const fromPath = route.query.from || "";

  if (fromPath.includes("community")) {
    return [
      ...baseCrumb,
      { name: "社区", path: "/community" },
      { name: "活动日历" },
    ];
  }

  return [...baseCrumb, { name: "活动日历" }];
});

// 活动类型
const eventTypes = [
  { label: "展览展示", value: "exhibition", icon: "Collection" },
  { label: "文艺演出", value: "performance", icon: "Medal" },
  { label: "非遗体验", value: "heritage", icon: "Present" },
  { label: "讲座论坛", value: "lecture", icon: "TrendCharts" },
  { label: "节庆活动", value: "festival", icon: "Sunny" },
];

// 状态相关
const selectedDate = ref(new Date());
const selectedTypes = ref([]);
const timeRange = ref("all");
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const showCreateEventDialog = ref(false);
const showContactDialog = ref(false);
const showRegisterDialog = ref(false);
const contactMessage = ref("");
const currentEvent = ref(null);

// 报名表单
const registrationForm = ref({
  name: "",
  phone: "",
  email: "",
  remark: "",
});

// 表单验证规则
const registrationRules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 本地测试数据
const mockEvents = [
  {
    id: 1,
    title: "贵港市非物质文化遗产展",
    description:
      "展示贵港市非物质文化遗产保护成果，包括传统工艺、民间艺术等多个领域。",
    image: "/images/events/heritage.jpg",
    type: "展览展示",
    status: "upcoming",
    startTime: "2024-03-25 09:00:00",
    endTime: "2024-03-30 17:00:00",
    location: "贵港市文化馆",
    registeredCount: 156,
    maxParticipants: 500,
    organizer: {
      name: "贵港市文化局",
      avatar: "/images/avatar/organizer1.jpg"
    }
  },
  {
    id: 2,
    title: "荷城古镇民俗文化节",
    description: "体验传统民俗文化，品尝地道美食，感受古镇魅力。",
    image: "/images/events/festival.jpg",
    type: "节庆活动",
    status: "ongoing",
    startTime: "2024-03-20 10:00:00",
    endTime: "2024-03-22 22:00:00",
    location: "荷城古镇",
    registeredCount: 2341,
    maxParticipants: 5000,
    organizer: {
      name: "贵港市旅游局",
      avatar: "/images/avatar/organizer2.jpg"
    }
  },
];

// 活动数据
const events = ref([]);

// 获取活动列表
const fetchEvents = async () => {
  loading.value = true;
  try {
    const response = await service.get("/public/events");
    console.log("后端返回的活动数据:", response);
    
    // 标准响应格式：{code: 200, message: '操作成功', data: [...]}
    const eventsData = response && response.data ? response.data : [];
                      
    if (eventsData && eventsData.length > 0) {
      // 处理后端返回的数据
      events.value = eventsData.map(event => ({
        ...event,
        // 确保字段格式一致
        type: event.type || "其他活动",
        // 处理图片路径 - 优先使用image字段，因为后端已返回该字段
        image: event.image || event.coverImage || "/images/events/default.jpg",
        // 字段名称映射 - 后端使用participantsCount
        registeredCount: event.participantsCount || 0,
        maxParticipants: event.maxParticipants || 100,
        description: event.description || "",
        // 确保组织者信息存在
        organizer: event.organizer || {
          name: "贵港文化旅游",
          avatar: "/images/avatar/default.jpg"
        }
      }));
      console.log("处理后的活动数据:", events.value);
    } else {
      console.log("后端返回的数据为空，使用测试数据");
      // 如果后端没有数据，使用测试数据
      events.value = [...mockEvents];
    }
  } catch (error) {
    console.error("获取活动失败:", error);
    // 使用测试数据
    events.value = [...mockEvents];
  } finally {
    loading.value = false;
  }
};

// 过滤活动
const filteredEvents = computed(() => {
  let result = events.value;

  // 按类型筛选
  if (selectedTypes.value.length > 0) {
    result = result.filter((event) => 
      selectedTypes.value.includes(event.type === "展览展示" ? "exhibition" : 
                                  event.type === "文艺演出" ? "performance" : 
                                  event.type === "非遗体验" ? "heritage" : 
                                  event.type === "讲座论坛" ? "lecture" : 
                                  event.type === "节庆活动" ? "festival" : "other")
    );
  }

  // 按时间范围筛选
  if (timeRange.value !== "all") {
    result = result.filter((event) => {
      if (timeRange.value === "upcoming") {
        return event.status === "upcoming";
      } else if (timeRange.value === "ongoing") {
        return event.status === "ongoing";
      } else if (timeRange.value === "ended") {
        return event.status === "ended";
      }
      return true;
    });
  }

  // 按搜索关键词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (event) =>
        event.title.toLowerCase().includes(query) ||
        event.description.toLowerCase().includes(query) ||
        event.location.toLowerCase().includes(query)
    );
  }

  return result;
});

// 当前页面显示的活动
const paginatedEvents = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredEvents.value.slice(startIndex, endIndex);
});

// 当前月份活动
const currentMonthEvents = computed(() => {
  const currentMonth = dayjs().format("YYYY-MM");
  return events.value.filter((event) => {
    const eventMonth = dayjs(event.startTime).format("YYYY-MM");
    return eventMonth === currentMonth;
  });
});

// 进行中的活动
const ongoingEvents = computed(() => {
  const now = dayjs();
  return events.value.filter((event) => {
    const start = dayjs(event.startTime);
    const end = dayjs(event.endTime);
    return start.isBefore(now) && end.isAfter(now);
  });
});

// 即将开始的活动
const upcomingEvents = computed(() => {
  const now = dayjs();
  return events.value.filter((event) => {
    const start = dayjs(event.startTime);
    return start.isAfter(now);
  });
});

// 选中日期的活动
const selectedDateEvents = computed(() => {
  if (!selectedDate.value) return [];
  const selectedMonth = selectedDate.value;
  return events.value.filter((event) => {
    const eventMonth = dayjs(event.startTime).format("YYYY-MM");
    return eventMonth === selectedMonth;
  });
});

// 格式化活动时间
const formatEventTime = (start, end) => {
  const startDate = dayjs(start);
  const endDate = dayjs(end);
  if (startDate.format("YYYY-MM-DD") === endDate.format("YYYY-MM-DD")) {
    return `${startDate.format("MM月DD日 HH:mm")} - ${endDate.format("HH:mm")}`;
  }
  return `${startDate.format("MM月DD日")} - ${endDate.format("MM月DD日")}`;
};

// 获取活动状态类型
const getEventStatusType = (status) => {
  const typeMap = {
    upcoming: "warning",
    ongoing: "success",
    ended: "info",
  };
  return typeMap[status] || "info";
};

// 获取活动状态文本
const getEventStatusText = (status) => {
  const textMap = {
    upcoming: "即将开始",
    ongoing: "进行中",
    ended: "已结束",
  };
  return textMap[status] || "未知状态";
};

// 获取活动类型的颜色类
const getEventTypeColor = (type) => {
  const colorMap = {
    展览展示: "event-type-blue",
    文艺演出: "event-type-green",
    非遗体验: "event-type-yellow",
    讲座论坛: "event-type-red",
    节庆活动: "event-type-purple",
  };
  return colorMap[type] || "bg-gray-500";
};

// 获取进度条状态
const getProgressStatus = (event) => {
  const percentage = (event.registeredCount / event.maxParticipants) * 100;
  if (event.status === "ended") return "exception";
  if (percentage >= 100) return "success";
  if (percentage >= 80) return "warning";
  return "";
};

// 处理报名
const handleRegister = (event) => {
  if (event.status === "ended") return;
  
  currentEvent.value = event;
  showRegisterDialog.value = true;
};

// 提交报名
const submitRegistration = async () => {
  try {
    // 可以调用API进行报名
    // const response = await service.post("/api/events/register", {
    //   eventId: currentEvent.value.id,
    //   ...registrationForm.value
    // });
    
    // 模拟报名成功
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 更新当前活动的报名人数
    const eventIndex = events.value.findIndex(e => e.id === currentEvent.value.id);
    if (eventIndex !== -1) {
      events.value[eventIndex].registeredCount += 1;
    }
    
    ElMessage.success(`已成功报名：${currentEvent.value.title}`);
    showRegisterDialog.value = false;
    
    // 重置表单
    registrationForm.value = {
      name: "",
      phone: "",
      email: "",
      remark: "",
    };
  } catch (error) {
    console.error("报名失败:", error);
    ElMessage.error("报名失败，请稍后重试");
  }
};

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理日期变化
const handleDateChange = (value) => {
  // 可以在这里添加额外的处理逻辑
};

// 日期快捷选项
const dateShortcuts = [
  {
    text: "本月",
    value: () => dayjs().format("YYYY-MM"),
  },
  {
    text: "上个月",
    value: () => dayjs().subtract(1, "month").format("YYYY-MM"),
  },
  {
    text: "下个月",
    value: () => dayjs().add(1, "month").format("YYYY-MM"),
  },
];

// 滚动到指定活动
const scrollToEvent = (eventId) => {
  const element = document.getElementById(`event-${eventId}`);
  if (element) {
    element.scrollIntoView({ behavior: "smooth", block: "center" });
    // 添加高亮效果
    element.classList.add("highlight-event");
    setTimeout(() => {
      element.classList.remove("highlight-event");
    }, 2000);
  }
};

// 处理活动点击
const handleEventClick = (event) => {
  // 添加来源参数
  router.push({
    path: `/community/event/${event.id}`,
    query: { from: "events" },
  });
};

// 处理登录
const handleLogin = () => {
  router.push("/login");
};

// 处理联系主办方
const handleContactOrganizer = (event) => {
  currentEvent.value = event;
  showContactDialog.value = true;
};

// 提交联系信息
const submitContact = async () => {
  if (!contactMessage.value.trim()) {
    ElMessage.warning("请输入留言内容");
    return;
  }
  
  try {
    // 模拟发送消息
    await new Promise(resolve => setTimeout(resolve, 800));
    ElMessage.success("消息已发送");
    showContactDialog.value = false;
    contactMessage.value = "";
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送失败，请稍后重试");
  }
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  // 搜索已经通过计算属性filteredEvents实现
};

// 处理时间范围变化
const handleTimeRangeChange = () => {
  currentPage.value = 1; // 重置到第一页
  // 时间范围筛选已经通过计算属性filteredEvents实现
};

// 处理活动类型变化
const handleTypeChange = () => {
  // 可以在这里添加额外的处理逻辑
  currentPage.value = 1; // 重置到第一页
};

// 初始化
onMounted(() => {
  fetchEvents();
});
</script>

<style lang="scss" scoped>
.events-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .page-header {
    @apply mb-6;

    h1 {
      @apply text-gray-900 dark:text-white;
    }

    p {
      @apply text-gray-600 dark:text-gray-400;
    }

    .back-btn {
      @apply hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors;
    }
  }

  .calendar-card {
    @apply backdrop-blur-sm;

    :deep(.custom-date-picker) {
      .el-input__wrapper {
        @apply dark:bg-gray-700/80 dark:border-gray-600 !shadow-none border border-gray-200;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05) !important;

        input {
          @apply dark:text-gray-300 text-gray-700 text-center font-medium;
          @apply dark:bg-gray-700/80 bg-white;

          &::placeholder {
            @apply dark:text-gray-500;
          }
        }

        .el-input__prefix,
        .el-input__suffix {
          @apply dark:text-gray-400;
        }

        .el-input__suffix {
          .el-input__suffix-inner {
            .el-icon {
              @apply dark:text-gray-400 text-gray-500;
              font-size: 16px;
            }
          }
        }

        &:hover {
          @apply dark:border-primary-500 dark:bg-gray-600/80 border-primary-500 bg-gray-50;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;

          input {
            @apply dark:bg-gray-600/80 bg-gray-50;
          }
        }
      }
    }

    :deep(.el-picker__popper) {
      @apply dark:bg-gray-800 dark:border-gray-700 border border-gray-200;
      box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06);

      .el-picker-panel__content {
        @apply dark:bg-gray-800 bg-white;

        .el-date-picker__header {
          @apply dark:text-gray-300 text-gray-700 mb-4;

          .el-picker-panel__icon-btn {
            @apply dark:text-gray-400 text-gray-600 hover:text-primary-500 dark:hover:text-primary-400;
            font-size: 16px;
          }

          .el-date-picker__prev-btn {
            @apply ml-2;
          }

          .el-date-picker__next-btn {
            @apply mr-2;
          }
        }

        .el-date-picker__header-label {
          @apply dark:text-gray-300 text-gray-700 hover:text-primary-500 dark:hover:text-primary-400 font-medium text-base;
        }

        .el-month-table {
          @apply border-spacing-1;

          td {
            .cell {
              @apply dark:text-gray-400 text-gray-600 hover:text-primary-500 dark:hover:text-primary-400;
              @apply py-3 rounded-lg transition-all duration-200;
              font-weight: 500;
              margin: 2px;

              &:hover {
                @apply bg-primary-50 dark:bg-primary-900/30;
              }
            }

            &.today {
              .cell {
                @apply text-primary-600 dark:text-primary-400 font-bold;
                @apply border border-primary-500 dark:border-primary-400;
              }
            }

            &.current {
              .cell {
                @apply bg-primary-500 dark:bg-primary-600 text-white;
                @apply shadow-sm;
              }
            }
          }
        }
      }

      .el-picker-panel__sidebar {
        @apply dark:bg-gray-800/95 dark:border-gray-700 border-r border-gray-200;
        @apply backdrop-blur-sm p-2;

        .el-picker-panel__shortcut {
          @apply dark:text-gray-400 text-gray-600;
          @apply block w-full text-center rounded-lg py-2 px-4 mb-1;
          @apply hover:bg-primary-50 dark:hover:bg-primary-900/30 hover:text-primary-500 dark:hover:text-primary-400;
          @apply transition-all duration-200;
        }
      }
    }
  }

  .category-card {
    .category-checkbox {
      @apply border-0 !m-0;

      :deep(.el-checkbox__input) {
        @apply mr-3;
      }

      &:deep(.el-checkbox__label) {
        @apply flex-1 text-gray-700 dark:text-gray-300;
      }

      &:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }

  .filter-card {
    :deep(.el-input__wrapper) {
      @apply dark:bg-gray-700 dark:border-gray-600;

      input {
        @apply dark:text-gray-300;

        &::placeholder {
          @apply dark:text-gray-500;
        }
      }
    }

    :deep(.el-radio-button__inner) {
      @apply dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600;

      &:hover {
        @apply dark:bg-gray-600;
      }
    }

    :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
      @apply dark:bg-primary-600 dark:text-white dark:border-primary-600;
    }
  }

  .event-card {
    @apply transform transition-all duration-300;

    &:hover {
      @apply -translate-y-1;
    }

    .image-placeholder {
      @apply w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700;

      .el-icon {
        @apply text-gray-400 dark:text-gray-500;
      }
    }

    .event-status-tag {
      @apply backdrop-blur-sm;

      &.el-tag--success {
        @apply bg-green-500/90 border-green-500;
      }

      &.el-tag--warning {
        @apply bg-yellow-500/90 border-yellow-500;
      }

      &.el-tag--info {
        @apply bg-gray-500/90 border-gray-500;
      }
    }

    .register-btn {
      @apply transition-all duration-300;

      &:not(:disabled) {
        @apply hover:scale-105;
      }

      &:disabled {
        @apply opacity-50 cursor-not-allowed;
      }
    }

    :deep(.el-progress-bar__outer) {
      @apply dark:bg-gray-700;
    }

    :deep(.el-progress-bar__inner) {
      @apply transition-all duration-500;
    }

    :deep(.el-progress.is-warning .el-progress-bar__inner) {
      @apply bg-yellow-500;
    }

    :deep(.el-progress.is-exception .el-progress-bar__inner) {
      @apply bg-gray-500;
    }
  }

  :deep(.el-pagination) {
    @apply dark:bg-transparent;

    .el-pagination__total {
      @apply dark:text-gray-400;
    }

    .btn-prev,
    .btn-next {
      @apply dark:bg-gray-700 dark:text-gray-300;
    }

    .el-pager li {
      @apply dark:bg-gray-700 dark:text-gray-300;

      &.active {
        @apply dark:bg-primary-600 dark:text-white;
      }

      &:hover {
        @apply dark:bg-gray-600;
      }
    }

    .el-pagination__sizes {
      .el-input__wrapper {
        @apply dark:bg-gray-700 dark:border-gray-600;
      }

      .el-input__inner {
        @apply dark:text-gray-300;
      }
    }
  }

  .highlight-event {
    animation: highlight 2s ease-in-out;
  }

  @keyframes highlight {
    0%,
    100% {
      @apply bg-white dark:bg-gray-800;
    }
    50% {
      @apply bg-primary-50 dark:bg-primary-900/20;
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .event-card {
    animation: fadeIn 0.5s ease-out;
    animation-fill-mode: both;

    @for $i from 1 through 10 {
      &:nth-child(#{$i}) {
        animation-delay: #{$i * 0.1}s;
      }
    }
  }

  // 活动类型颜色样式
  .event-type-blue {
    @apply bg-blue-500;
    &.dark {
      background-color: theme("colors.blue.400");
    }
  }

  .event-type-green {
    @apply bg-green-500;
    &.dark {
      background-color: theme("colors.green.400");
    }
  }

  .event-type-yellow {
    @apply bg-yellow-500;
    &.dark {
      background-color: theme("colors.yellow.400");
    }
  }

  .event-type-red {
    @apply bg-red-500;
    &.dark {
      background-color: theme("colors.red.400");
    }
  }

  .event-type-purple {
    @apply bg-purple-500;
    &.dark {
      background-color: theme("colors.purple.400");
    }
  }

  .card-header {
    @apply flex items-center justify-between;

    .header-actions {
      @apply flex items-center gap-4;
    }
  }
}
</style>
